﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SocketUtil
{
    public class SocketClient
    {
        string _ip;
        int _port = 0;
        Socket _socket = null;

        byte[] buffer = new byte[1024 * 1024 * 2];

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip">连接服务器的IP</param>
        /// <param name="port">连接服务器的端口</param>
        public SocketClient(string ip,int port)
        {
            this._ip = ip;
            this._port = port;
        }
        public SocketClient(int port)
        {
            this._ip = "127.0.0.1";
            this._port = port;
        }

        /// <summary>
        /// 开启服务连接服务器
        /// </summary>
        public void StartClient()
        {
            try
            {
                //1.实例化Socket IP4寻址地址,流式传输,TCP协议
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //2.创建IP对象
                IPAddress address = IPAddress.Parse(_ip);

                //3.创建网络端口 ip和端口
                IPEndPoint endPoint = new IPEndPoint(address, _port);

                //4.建立连接
                _socket.Connect(endPoint);
                Console.WriteLine("连接服务器成功");

                //5.接收数据
                int length = _socket.Receive(buffer);
                Console.WriteLine($"接收服务器{_socket.RemoteEndPoint},消息:{Encoding.UTF8.GetString(buffer, 0, length)}");

                //6.向服务器发送消息
                for (int i = 0; i < int.MaxValue; i++)
                {
                    Thread.Sleep(2000);
                    string sendMessage = $"客户端发送的消息,当前时间{DateTime.Now}";

                    _socket.Send(Encoding.UTF8.GetBytes(sendMessage));
                    Console.WriteLine($"向服务发送的消息:{sendMessage}");
                }

            }catch(Exception ex)
            {
                _socket.Shutdown(SocketShutdown.Both);
                _socket.Close();
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("发送消息结束");
            Console.ReadKey();




        }
    }
}
